package com.leaguefox.web.server;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.leaguefox.domain.Player;
import com.leaguefox.domain.dao.PlayerDao;
import com.leaguefox.web.client.LeagueFoxService;
import com.leaguefox.web.shared.FieldVerifier;
import com.leaguefox.web.shared.domain.dto.PlayerDto;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class LeagueFoxServiceImpl extends RemoteServiceServlet implements
		LeagueFoxService, Controller {
 
	private PlayerDao playerDao;

	public LeagueFoxServiceImpl() {
		try {
			init(null);
		} catch (ServletException e) {
			throw new RuntimeException(e);
		}
	}

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid.
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back
			// to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	@Override
	public ArrayList<PlayerDto> getAllPlayers() {
		List<Player> players = playerDao.findAll();
		ArrayList<PlayerDto> ret = new ArrayList<PlayerDto>();
		
		for(Player player : players) {
			ret.add(new PlayerDto(player.getId(), player.getSurname())); 
		}
		
		System.out.println(ret);
		return ret; 
	}

	@Required
	public void setPlayerDao(PlayerDao playerDao) {
		this.playerDao = playerDao;
	}

	public PlayerDao getPlayerDao() {
		return playerDao;
	}

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		super.doPost(request, response);
		return null;
	}

	@Override
	public ArrayList<PlayerDto> deletePlayers(ArrayList<Long> ids) {
		// TODO Auto-generated method stub
		return null;
	}
}
